var myDate = new Date();             //获取当前日期
var year = myDate.getFullYear();     //获取当前年份
var month = myDate.getMonth();       //获取当前月份(0-11,0代表1月)
var html = "", html2 = "", html3 = "";
var dataMonth, dataMonth1, dataMonth2;
var uid, goods_id, number, token;
var totalDate;

switch (month + 1) {
    case (1):
        html3 = "一月份";
        html = "二月份";
        html2 = "三月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (2):
        html3 = "二月份";
        html = "三月份";
        html2 = "四月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (3):
        html3 = "三月份";
        html = "四月份";
        html2 = "五月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (4):
        html3 = "四月份";
        html = "五月份";
        html2 = "六月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (5):
        html3 = "五月份";
        html = "六月份";
        html2 = "七月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (6):
        html3 = "六月份";
        html = "七月份";
        html2 = "八月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (7):
        html3 = "七月份";
        html = "八月份";
        html2 = "九月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (8):

        html3 = "八月份";
        html = "九月份";
        html2 = "十月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (9):
        html3 = "九月份";
        html = "十月份";
        html2 = "十一月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        dataMonth2 = year + "年" + Number(month + 3) + "月";
        break;
    case (10):
        html3 = "十月份";
        html = "十一月份";
        html2 = "十二月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        dataMonth1 = year + "年" + Number(month + 2) + "月";
        year++;
        dataMonth2 = year + "年" + Number(month - 9) + "月";
        break;
    case (11):
        html3 = "十一月份";
        html = "十二月份";
        html2 = "一月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        year++;
        dataMonth1 = year + "年" + Number(month - 10) + "月";
        dataMonth2 = year + "年" + Number(month - 9) + "月";

        break;
    case (12):
        html3 = "十二月份";
        html = "一月份";
        html2 = "二月份";
        dataMonth = year + "年" + Number(month + 1) + "月";
        year++;
        dataMonth1 = year + "年" + Number(month - 10) + "月";
        dataMonth2 = year + "年" + Number(month - 9) + "月";
        break;
}

var span = document.getElementsByClassName("nick-calendar-date");
span[0].innerHTML = html3;
span[1].innerHTML = html;
span[2].innerHTML = html2;
$(".span1").attr("data-date", dataMonth);
$(".span2").attr("data-date", dataMonth1);
$(".span3").attr("data-date", dataMonth2);


if (ismobile() == 0) {

    window.android.getAndroidId("okok");
}

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallManPowerCalenderModel.postMessage(message);
}

//scheduleAjax(27, 47, 1, "1D616DD2-1B71-8276-A2A0-8699F5FE8DC4");

function getScheduleId(mmm) {

    if (ismobile() == 1) {

        CallManPowerCalenderModel.jsCallOCWithSendId();

    } else if (ismobile() == 0) {

        window.android.getAndroidId("okok");
    }

}

function receive_android_projectid(k) {

    var obj = $.parseJSON(k);

    uid = obj.serverid;

    goods_id = obj.goods_id;

    number = obj.uu_number;

    token = obj.TOKEN;

    //console.log(obj)

    scheduleAjax(uid, goods_id, number, token);
}

function receiveiOSVcData(i) {

    var obj = $.parseJSON(i);

    //alert(JSON.stringify(i))

    uid = obj.serverid;

    goods_id = obj.goods_id;

    number = obj.uu_number;

    token = obj.TOKEN;

    scheduleAjax(uid, goods_id, number, token);
}

function scheduleAjax(uid, goods_id, number, token) {

    $.ajax({

        type: "POST",

        url: url + "users/calendarinfo",

        dataType: "json",

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);

        },
        data: {

            "uid": uid,

            "goods_id": goods_id,

            "uu_number": number
        },

        success: function (data) {

            console.log(data);

            if (data.data.codes == 200) {

                var i = new Date().getMonth() + 1;

                handleResult(data);

                calendarNick(0, i + "月");

                clickMonth();


            } else {
                console.log(data.data.msg)
            }

        },
        error: function (info) {

            console.log(info)

        }
    })
}
var arr = [];

var monthArr = [];

function TempArr() {
    this.red = new Array(0);
    this.green = new Array(0);
    this.half = new Array(0);
}

function Month(currenYear, currenMonth, lenght) {
    this.currenYear = currenYear;
    this.currenMonth = currenMonth;
    this.dates = new Array(lenght);
}

function DateInfo(number, flag) {
    this.number = number;
    this.flag = flag;
}

function getDateNum(year, month) {
    var d = new Date(year, month, 0);
    return d.getDate();
}

function handleResult(data) {
    arr.length = 0;
    arr[0] = new TempArr();
    arr[1] = new TempArr();
    arr[2] = new TempArr();
    var firstMonth = GetRequest($(".span1").data("date")).month;
    var secordMonth = GetRequest($(".span2").data("date")).month;
    var threeMonth = GetRequest($(".span3").data("date")).month;

    if (data.data.data.server_ing != null && data.data.data.server_ing.whole_date != null) {
        var serverIng = data.data.data.server_ing.whole_date;
        serverIng.forEach(function (item, i) {
            var serverDate = new Date(item);
            var month = (serverDate.getMonth() + 1) % 12;
            if (Number(firstMonth) == Number(month)) {
                arr[0].red.push(serverDate);
            }
            if (Number(secordMonth) == Number(month)) {
                arr[1].red.push(serverDate);
            }
            if (Number(threeMonth) == Number(month)) {
                arr[2].red.push(serverDate);
            }
        });
    }

    if (data.data.data.server_wait != null && data.data.data.server_wait.whole_date != null) {
        var serverWait = data.data.data.server_wait.whole_date;
        serverWait.forEach(function (item, i) {
            var serverDate = new Date(item);
            var month = (serverDate.getMonth() + 1) % 12;
            if (Number(firstMonth) == Number(month)) {
                arr[0].green.push(serverDate);
            }
            if (Number(secordMonth) == Number(month)) {
                arr[1].green.push(serverDate);
            }
            if (Number(threeMonth) == Number(month)) {
                arr[2].green.push(serverDate);
            }
        });
    }

    if (data.data.data.server_ing != null && data.data.data.server_ing.half_date != null) {
        var serverWait = data.data.data.server_ing.half_date;
        serverWait.forEach(function (item, i) {
            var serverDate = new Date(item);
            var month = (serverDate.getMonth() + 1) % 12;
            if (Number(firstMonth) == Number(month)) {
                arr[0].half.push(serverDate)
            }
            if (Number(secordMonth) == Number(month)) {
                arr[1].half.push(serverDate)
            }
            if (Number(threeMonth) == Number(month)) {
                arr[2].half.push(serverDate)
            }
        });
    }

    if (data.data.data.server_wait != null && data.data.data.server_wait.half_date != null) {
        var serverWait = data.data.data.server_wait.half_date;
        serverWait.forEach(function (item, i) {
            var serverDate = new Date(item);
            var month = (serverDate.getMonth() + 1) % 12;
            if (Number(firstMonth) == Number(month)) {
                arr[0].half.push(serverDate)
            }
            if (Number(secordMonth) == Number(month)) {
                arr[1].half.push(serverDate)
            }
            if (Number(threeMonth) == Number(month)) {
                arr[2].half.push(serverDate)
            }
        });
    }

    var today = new Date(data.data.data.current_time * 1000).getDate();

    //console.log(arr)

    render(today);

}

function render(today) {
    //var firstYear = $(".span1").data("date").slice(0, 4);
    //var secorYear = $(".span2").data("date").slice(0, 4);
    //var threeYear = $(".span3").data("date").slice(0, 4);
    //var firstMonth = $(".span1").data("date").slice(5, 6);
    //var secordMonth = $(".span2").data("date").slice(5, 6);
    //var threeMonth = $(".span3").data("date").slice(5, 6);
    var firstYear = GetRequest($(".span1").data("date")).year;
    var secorYear = GetRequest($(".span2").data("date")).year;
    var threeYear = GetRequest($(".span3").data("date")).year;

    var firstMonth = GetRequest($(".span1").data("date")).month;
    var secordMonth = GetRequest($(".span2").data("date")).month;
    var threeMonth = GetRequest($(".span3").data("date")).month;

    monthArr[0] = new Month(firstYear, firstMonth, getDateNum(firstYear, firstMonth));
    monthArr[1] = new Month(secorYear, secordMonth, getDateNum(secorYear, secordMonth));
    monthArr[2] = new Month(threeYear, threeMonth, getDateNum(threeYear, threeMonth));


    arr.forEach(function (item, i) {
        if (item) {
            var greenArray = item.green;
            var redArray = item.red;
            var halfArray = item.half;

            for (var j = 0; j < monthArr[i].dates.length; j++) {
                if (greenArray.length > 0) {
                    if (greenArray[0].getDate() == j + 1) {
                        if (i == 0 && j + 1 < today) {
                            monthArr[i].dates[j] = new DateInfo(j + 1, "nomal");
                        } else {
                            monthArr[i].dates[j] = new DateInfo(j + 1, "green");
                        }
                        greenArray.shift();
                        continue;
                    }
                }
                if (redArray.length > 0) {
                    if (redArray[0].getDate() == j + 1) {
                        if (i == 0 && j + 1 < today) {
                            monthArr[i].dates[j] = new DateInfo(j + 1, "nomal");
                        } else {
                            monthArr[i].dates[j] = new DateInfo(j + 1, "red");
                        }
                        redArray.shift();
                        continue;
                    }
                }
                if (halfArray.length > 0) {
                    if (halfArray[0].getDate() == j + 1) {
                        if (i == 0 && j + 1 < today) {
                            monthArr[i].dates[j] = new DateInfo(j + 1, "nomal");
                        } else {
                            monthArr[i].dates[j] = new DateInfo(j + 1, "half");
                        }
                        halfArray.shift();
                        continue;
                    }
                }
                if (monthArr[i].dates[j] == null) {
                    monthArr[i].dates[j] = new DateInfo(j + 1, "nomal");
                }
            }
        }
    });
}

function clickMonth() {

    $(".nick-calendar-date").on("click", function () {

        $(".nick-calendar-date").removeClass("active");

        $(this).addClass("active");

        var index = $(this).data("index");

        var mon = $(this).data("date").slice(5);

//            $(".header").html(mon);
//            $(".date>div").hide();
//            $("#nickCalendar" + index).show();
        calendarNick(
//                    {
//                wrapId: "nickCalendar" + index//日历容器id
//                //triggerId: 'date1'//触发容器id
//            },
            index, mon);

    });
}

function calendarNick(index, mon) {
    //console.log(index, mon)
    //参数保存在此对象中

    var opt = {
//            opts: options

    };
    var obj = {
        //填充日历
        fillDate: function (year, month) {

            //console.log(year, month)
            //本月份第一天是星期几-为显示上个月的天数做铺垫
            var first_day = new Date(year, month, 1).getDay();
            //如果刚好是星期天，则空出一行（显示上个月的天数）
            //first_day = first_day == 0 ? 7 : first_day;
            //本月份最后一天是几号
            var final_date = new Date(year, month + 1, 0).getDate();
            //上个月的最后一天是几号
            var last_date = new Date(year, month, 0).getDate();
            //剩余的格子数--即排在末尾的格子数
            var surplus = 35 - first_day - final_date;
            /*填充日历执行*/
            var html = '';
            //上个月的显示天数
            for (var i = 0; i < first_day; i++) {
                html += '<span class="prev-date-nick">' + (last_date - (first_day - 1) + i) + '</span>';
            }
            //本月的显示天数
            for (var j = 0; j < monthArr[index].dates.length; j++) {
                html += '<span class="date-nick ' + monthArr[index].dates[j].flag + '" >' + (j + 1) + '</span>';
            }
            //下个月的显示天数
            for (var k = 0; k < surplus; k++) {
                html += '<span class="next-date-nick">' + (k + 1) + '</span>';
            }

            //fill
            opt.oBody.innerHTML = html;
            // 当天
            // if (year == new Date().getFullYear() && month == new Date().getMonth()) {
            //     opt.oBody.getElementsByTagName('span')[first_day + opt.date - 1].className = 'nick-calendar-current date-nick';
            // }


//
        },

        init: function () {//初始化
            //创建日历容器固定结构，每次切换日期值即可
//                var div = document.getElementsByClassName("bd_div");
//                div.setAttribute('id', opt.opts.wrapId);
//                div.innerHTML = '';
//                document.getElementsByClassName("bd")[0].appendChild(div);

            $(".header").html(mon);
            opt.oWrap = document.getElementsByClassName("bd");//日历容器
            opt.oBody = opt.oWrap[0];//日期容器
            //   opt.oBody = div;//日期容器
            //  console.log(div)

            opt.year = 0;//年
            opt.month = 0;//月
            opt.date = 0;//日

            opt.year = monthArr[index].currenYear;
            opt.month = Number(monthArr[index].currenMonth) - 1;

            //console.log(opt.year, opt.month)

            // 初始化--填充日历
            this.fillDate(opt.year, opt.month);
            //设置日历容器位置
            //opt.oWrap.style.position = 'absolute';
            //opt.oWrap.style.display = 'block';//默认隐藏日历容器
        }
    };
    obj.init();//初始化
}

function ismobile() {
    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                qq: u.match(/\sQQ/i) == " qq" //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };
    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
}
//格式化时间
function timeFormatDate(timeStamp) {

    var tmpTime = Date.parse(new Date(timeStamp));

    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    var newDate = new Date();
    newDate.setTime(tmpTime);
    return newDate.format('yyyy-MM-dd');
}
//将  '2018年9月'  =>  {'year':2018,'month':9}
function GetRequest(url) {//'2018年9月'=》{'year':2018,'month':9}

    var theRequest = new Object();

    if (url.indexOf("年") != -1) {

        var str = url.substr(0, url.length - 1);

        var year = url.indexOf("年");

        theRequest.year = url.slice(0, year);

        theRequest.month = str.slice(year + 1);

    }
    return theRequest;
}

